package com.zhongxi.guoyuan.view.user;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.code.CodeResult;
import com.zhongxi.guoyuan.entity.user.RegisterCheckResult;
import com.zhongxi.guoyuan.entity.user.UserData;
import com.zhongxi.guoyuan.entity.user.UseInfo;
import com.zhongxi.guoyuan.entity.user.UserResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.view.MainHomeActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class ForgotPasswordActivity extends BaseActivity implements View.OnClickListener {

    private Button btSend;
    private EditText etPhone;
    private EditText etCode;
    private Button btSure;
    private EditText etPassword;
    private String code;
    private String phone;
    private String type;
    private Map<String, String> map = new HashMap<String, String>();
    private String mMsgid;

    /*定义一个倒计时的内部类*/
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长，和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btSend.setClickable(false);
            btSend.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {//计时完毕时触发
            btSend.setText("发送验证码");
            btSend.setClickable(true);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_forgot);
        initTitle();
        tvTitle.setText("忘记密码");
        etPhone = (EditText) findViewById(R.id.etPhone);
        btSend = (Button) findViewById(R.id.btSend);
        etCode = (EditText) findViewById(R.id.etCode);
        btSure = (Button) findViewById(R.id.btSure);
        etPassword = (EditText) findViewById(R.id.etPassword);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        btSend.setOnClickListener(this);
        btSure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.btSend:
                phone = etPhone.getText().toString().trim();
                sendCode();
                break;
            case R.id.btSure:
                code = etCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    showShortToast("验证码不能为空");
                } else {
                    check();
                }
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendCode() {
        if (TextUtils.isEmpty(phone)) {
            showShortToast("手机号不能为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else {
            type = "sendcode";
            TimeCount time = new TimeCount(60000, 1000);
            time.start();
            map.clear();
            map.put("mobilenum", phone);
            getServer(Url.SEND_CODE, map, "", false, null, "post");
        }
    }

    /**
     * 注册前校验
     */
    private void check() {

        type = "registerCheck";
        map.clear();
        map.put("mobilenum", phone);
        map.put("veriycode", code);
        map.put("msgid", mMsgid);
        getServer(Url.REGISTER_CHECK, map, "", false, null, "post");
    }

    /**
     * 重置密码
     *
     * @param id
     */
    private void setPassword(String id) {
        Map<String, String> map = new HashMap<>();
        map.clear();
        type = "setPassword";
        map.put("useid", id);
        map.put("newpwd", MyApplication.getInstance().descsc(etPassword.getText().toString().trim()));
        map.put("oldpwd", "");
        getServer(Url.SET_PWD, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if ("sendcode".equals(type)) {
                CodeResult result = gson.fromJson(response, CodeResult.class);
                if (null != result && !"".equals(result)) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                mMsgid = result.getMsgid();
            } else if ("registerCheck".equals(type)) {
                RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
                if (null != result && !"".equals(result)) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (!TextUtils.isEmpty(result.getId())) {
                    setPassword(result.getId());
                }
            } else if ("setPassword".equals(type)) {
                UserResult result = gson.fromJson(response, UserResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getData() && !"".equals(result.getData())) {
                    UserData data = result.getData();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("phone", result.getData().getMphone()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("userid", result.getData().getId()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("username", result.getData().getUsername()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", result.getData().getShopname()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", result.getData().getAvatar()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("time", result.getData().getCtime()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", result.getData().getAppopenid()).commit();
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //股东
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(data.getIsshareholders())).commit();
                    }
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  // 消费收益人
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", "1".equals(data.getIsbeneficiary())).commit();
                    }
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //商家
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", "1".equals(data.getIsmerchants())).commit();
                    }

                    if (null != String.valueOf(data.getIspartner())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("partener", 1 == data.getIspartner()).commit();
                    }
                    JPushInterface.setAlias(context, MyApplication.getInstance().getUserId(), new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            if (i == 0) {
                                Log.d("LoginActivity", s);
                            }
                        }
                    });
                }
                if (null != result.getExtend() && !"".equals(result.getExtend())) {
                    UseInfo extend = result.getExtend();
                    if (null != extend.getInnercurrency() && !"".equals(extend.getInnercurrency())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("inner", extend.getInnercurrency()).commit();
                    }
                    if (null != extend.getSharesgains() && !"".equals(extend.getSharesgains())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("share", DataUtil.formatData(extend.getSharesgains())).commit();  //股份收益
                    }
                }
                finish();
                startAct(MainHomeActivity.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        try {
            Gson gson = new Gson();
            BaseResponse mBaseResponse = gson.fromJson(response, BaseResponse.class);
            if (null != mBaseResponse.getSafeobj() && !"".equals(mBaseResponse.getSafeobj())) {
                MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
            }
            if (mBaseResponse.getCode() == 1000) {
//                showShortToast("参数错误");
            } else if (mBaseResponse.getCode() == 1100) {
                showShortToast("短信重复请求");
            } else if (mBaseResponse.getCode() == 1101) {
                showShortToast("短信服务失效");
            } else if (mBaseResponse.getCode() == 4001) {
                if (!TextUtils.isEmpty(mBaseResponse.getId())) {
                    setPassword(mBaseResponse.getId());
                }

            } else if (mBaseResponse.getCode() == 1999) {
                showShortToast("Url 无效");
            } else if (mBaseResponse.getCode() == 4003) {
                showShortToast("老密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void processOldUser(String response) {
        super.processOldUser(response);
        Gson gson = new Gson();
        RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
        if (null != result && !"".equals(result.getSafeobj())) {
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        }
        showShortToast("老用户,未设置密码");
        Intent mIntent = new Intent(this, SetPasswordActivity.class);
        mIntent.putExtra("id", result.getId());
        startActivity(mIntent);
        finish();
    }
}
